package com.zh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.common.QueryPageParam;
import com.zh.common.Result;
import com.zh.entity.Menu;
import com.zh.entity.User;
import com.zh.mapper.UserMapper;
import com.zh.service.MenuService;
import com.zh.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zh
 * @since 2025-03-29
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private MenuService menuService;

    @Override
    public Result register(User user) {
        try {
            // 参数校验
            if (user.getNo() == null || user.getNo().trim().isEmpty()) {
                return Result.result(400, "账号不能为空", null, 0L);
            }
            if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
                return Result.result(400, "密码不能为空", null, 0L);
            }

            // 检查账号是否已存在
            List<User> users = this.lambdaQuery()
                    .eq(User::getNo, user.getNo())
                    .list();
            if (!users.isEmpty()) {
                return Result.result(400, "账号已存在", null, 0L);
            }

            // 设置默认角色为普通用户
            user.setRoleId(2);
            user.setIsValid("Y"); //默认有效

            // 保存用户
            boolean isSuccess = this.save(user);
            if (!isSuccess) {
                return Result.result(500, "注册失败", null, 0L);
            }
            return Result.success(user, 0L);

        } catch (Exception e) {
            log.error("注册异常：账号={}, 密码={}", user.getNo(), user.getPassword(), e);
            return Result.result(500, "系统服务异常", null, 0L);
        }
    }

    @Override
    public Result login(User user, HttpSession session) {
        try {
            // 参数校验
            if (user.getNo() == null || user.getNo().trim().isEmpty()) {
                return Result.result(400, "账号不能为空", null, 0L);
            }
            if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
                return Result.result(400, "密码不能为空", null, 0L);
            }

            // 查询用户
            List<User> users = this.lambdaQuery()
                    .eq(User::getNo, user.getNo())
                    .eq(User::getPassword, user.getPassword())
                    .list();

            // 结果处理
            if (users.isEmpty()) {
                return Result.result(401, "账号或密码错误", null, 0L);
            }

            User loginUser = users.get(0);

            // 返回脱敏后的用户数据
            User safeUser = new User();
            safeUser.setId(loginUser.getId());
            safeUser.setName(loginUser.getName());
            safeUser.setRoleId(loginUser.getRoleId());
            safeUser.setNo(loginUser.getNo());

            session.setAttribute("user", safeUser);
            List<Menu> menusList = menuService.lambdaQuery().like(Menu::getMenuRight, safeUser.getRoleId()).list();
            log.info("菜单列表：{}", menusList);
            HashMap res = new HashMap();
            res.put("user", safeUser);
            res.put("menu", menusList);
            return Result.success(res, 0L);

        } catch (Exception e) {
            log.error("登录异常：账号={}", user.getNo(), e);
            return Result.result(500, "系统服务异常", null, 0L);
        }
    }

    @Override
    public Result logout(HttpSession session) {
        try {
            session.removeAttribute("user");
            session.invalidate();
            return Result.success("退出成功", 0L);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result listPage(QueryPageParam queryPageParam) {
        // 保持使用HashMap类型
        HashMap param = queryPageParam.getParam();

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        // 处理姓名查询（带空值检查和trim）
        if (param.containsKey("name")) {
            Object nameObj = param.get("name");
            if (nameObj != null && !nameObj.toString().trim().isEmpty()) {
                wrapper.like(User::getName, nameObj.toString().trim());
            }
        }

        // 处理账号查询（带空值检查和trim）
        if (param.containsKey("no")) {
            Object noObj = param.get("no");
            if (noObj != null && !noObj.toString().trim().isEmpty()) {
                wrapper.eq(User::getNo, noObj.toString().trim());
            }
        }

        if (param.containsKey("roleId")) {
            Object roleIdObj = param.get("roleId");
            if (roleIdObj != null) { // 新增空值检查
                try {
                    int roleId = Integer.parseInt(roleIdObj.toString());
                    wrapper.eq(User::getRoleId, roleId);
                } catch (NumberFormatException e) {
                    log.error("非法角色ID格式: {}", roleIdObj);
                }
            }
        }

        // 分页查询
        Page<User> page = new Page<>(
                queryPageParam.getPageNum(),
                queryPageParam.getPageSize()
        );

        IPage<User> result = this.page(page, wrapper);

        // 添加调试日志
        log.info("请求参数详情：name={}, no={}, roleId={}",
                param.get("name"), param.get("no"), param.get("roleId"));

        return Result.success(result.getRecords(), result.getTotal());
    }
}
